/**
 * 
 */
package com.gf.pf.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gf.common.BaseController;
import com.gf.common.Md5Encryption;
import com.gf.common.ResultMessage;
import com.gf.common.UUIDGenerator;
import com.gf.pf.model.Flexigrid;
import com.gf.pf.model.User;
import com.gf.pf.model.UserJob;
import com.gf.pf.model.UserRole;
import com.gf.pf.service.DepartmentService;
import com.gf.pf.service.MyBatisService;
import com.gf.pf.service.UserService;

/**
 * @description 用户管理
 * @date   Mar 7, 2015
 */
@Controller
@RequestMapping("/pf/user")
public class UserController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
	
	/**
	 * 用户列表
	 */
	private String USER_LIST = "pf/userList";
	
	/**
	 * 添加用户
	 */
	private String USER_ADD = "pf/userAdd";
	
	/**
	 * 修改用户
	 */
	private String USER_MODIFY = "pf/userModify";
	
	/**
	 * 职位选择
	 */
	private String CHOOSE_JOB = "pf/chooseJob";
	
	/**
	 * 角色选择
	 */
	private String CHOOSE_ROLE = "pf/chooseRole";
	
	/**
	 * 修改密码
	 */
	private final String PASSWORD_MODIFY = "pf/modifyPwd";
	
	/**
	 * 每页记录数
	 */
	private final String PAGE_SQL_ID = "pf.user.userList";
	
	/**
	 * 总记录数
	 */
	private final String TOTAL_SQL_ID = "pf.user.total";
	
	/**
	 * 部门ID为空！
	 */
	private String department_id_empty = "部门ID为空！";
	
	/**
	 * 用户ID为空！
	 */
	private String user_id_empty = "用户ID为空！";
	
	@Autowired
	MyBatisService myBatisService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	DepartmentService departmentService;
	
	/**
	 * 
	 * @description 用户管理列表
	 * @return String
	 */
	@RequestMapping(value = "/flUser", method = RequestMethod.GET)
	public String userListForward() {
		return this.USER_LIST;
	}
	
	/**
	 * 
	 * @description 查询部门下的所有用户
	 * @return Flexigrid
	 */
	@RequestMapping(value = "/dataGrid", method = RequestMethod.POST)
	@ResponseBody
	public Flexigrid userListContent(User user, Flexigrid flex) {
		if(StringUtils.isEmpty(user.getUserDepartmentId())) {
			user.setUserDepartmentId(super.ROOT_ID);
		}
		flex.setObj(user);
		flex.setRowStart((flex.getPage() - 1) * flex.getRp());
		flex.setRowEnd(flex.getPage() * flex.getRp());
		List<?> rows = myBatisService.getList(this.PAGE_SQL_ID, flex);
		int total = myBatisService.count(this.TOTAL_SQL_ID, flex);
		flex.setTotal(total);
		flex.setRows(rows);
		return flex;
	}
	
	/**
	 * 
	 * @description 添加用户跳转
	 * @return String
	 */
	@RequestMapping(value = "/faUser", method = RequestMethod.GET)
	public String userAddForward(String depId, Model model) {
		if(!StringUtils.isEmpty(depId)) {
			model.addAttribute("depId", depId);
		} else {
			LOGGER.error(this.department_id_empty);
			return this.USER_LIST;
		}
		return this.USER_ADD;
	}
	
	/**
	 * 
	 * @description 添加用户
	 * @return String
	 */
	@RequestMapping(value = "/aUser", method = RequestMethod.POST)
	@ResponseBody
	public ResultMessage userAdd(User user) {
		if(StringUtils.isEmpty(user.getUserDepartmentId())) {
			LOGGER.error(this.department_id_empty);
		}
		user.setId(UUIDGenerator.getInstance().getUUID32());
		Integer result = userService.saveUser(user);
		if(result > 0) {
			super.resultMessage.setFlag(super.RESULTMESSAGE_SUCCESS);
			super.resultMessage.setMsg("用户保存成功！");
		} else {
			super.resultMessage.setFlag(super.RESULTMESSAGE_FAIL);
			super.resultMessage.setMsg("用户保存失败！");
		}
		return super.resultMessage;
	}
	
	/**
	 * 
	 * @description 用户修改跳转
	 * @return String
	 */
	@RequestMapping(value = "/fmUser", method = RequestMethod.GET)
	public String useRModifyForward(String userId, Model model) {
		if(!StringUtils.isEmpty(userId)) {
			User user = userService.getUserById(userId);
			model.addAttribute("user", user);
		} else {
			LOGGER.error(this.user_id_empty);
			return this.USER_LIST;
		}
		return this.USER_MODIFY;
	}
	
	/**
	 * 
	 * @description 用户修改
	 * @return ResultMessage
	 */
	@RequestMapping(value = "/mUser", method = RequestMethod.POST)
	@ResponseBody
	public ResultMessage useRModify(User user) {
		if(StringUtils.isEmpty(user.getId())) {
			LOGGER.error(this.user_id_empty);
		}
		
		User u = userService.getUserById(user.getId());
		u.setUserLoginName(user.getUserLoginName());
		u.setUserName(user.getUserName());
		u.setUserPhone(user.getUserPhone());
		u.setUserTel(user.getUserTel());
		u.setUserEmail(user.getUserEmail());
		u.setUserMemo(user.getUserMemo());
		u.setUserIsvalid(user.getUserIsvalid());
		
		Integer result = userService.modifyUser(u);
		if(result > 0) {
			super.resultMessage.setFlag(super.RESULTMESSAGE_SUCCESS);
			super.resultMessage.setMsg("用户修改成功！");
		} else {
			super.resultMessage.setFlag(super.RESULTMESSAGE_FAIL);
			super.resultMessage.setMsg("用户修改失败！");
		}
		return super.resultMessage;
	}
	
	/**
	 * 
	 * @description 删除用户
	 * @return ResultMessage
	 */
	@RequestMapping(value = "/dUser", method = RequestMethod.POST)
	@ResponseBody
	public ResultMessage userDelete(String userId) {
		if(StringUtils.isEmpty(userId)) {
			LOGGER.error(this.user_id_empty);
		}
		
		Integer result = userService.deleteUser(userId);
		if(result > 0) {
			super.resultMessage.setFlag(super.RESULTMESSAGE_SUCCESS);
			super.resultMessage.setMsg("用户删除成功！");
		} else {
			super.resultMessage.setFlag(super.RESULTMESSAGE_FAIL);
			super.resultMessage.setMsg("用户删除失败！");
		}
		return super.resultMessage;
	}
	
	/**
	 * 
	 * @description 选择职位
	 * @return String
	 */
	@RequestMapping(value = "/chooseJob", method = RequestMethod.GET)
	public String chooseJob(String userId, Model model) {
		if(StringUtils.isEmpty(userId)) {
			LOGGER.error(this.user_id_empty);
		}
		
		User user = userService.getUserById(userId);
		model.addAttribute("user", user);
		
		List<Map<String, String>> mapList = userService.jobByUserId(userId);
		StringBuffer sb = new StringBuffer();
		if(null != mapList && mapList.size() > 0) {
			for(Map<String, String> map : mapList) {
				sb.append(map.get("JOBID") + ",");
			}
		}
		String temp = sb.toString();
		if(temp.length() > 0) {
			temp = temp.substring(0, temp.length() - 1);
		}
		model.addAttribute("jobIds", temp);
		return this.CHOOSE_JOB;
	}
	
	/**
	 * 
	 * @description 保存用户职位
	 * @return ResultMessage
	 */
	@RequestMapping(value = "/saveChooseJob", method = RequestMethod.POST)
	@ResponseBody
	public ResultMessage saveChooseJob(String userId, String jobIds) {
		if(StringUtils.isEmpty(userId)) {
			LOGGER.error(this.user_id_empty);
		}
		
		if(StringUtils.isEmpty(jobIds)) {
			LOGGER.error("职位IDS为空！");
		}
		
		Integer result = userService.deleteJobByUser(userId);
		if(result > 0) {
			LOGGER.error("删除用户(" + userId + ")包含职位成功！");
		} else {
			LOGGER.error("删除用户(" + userId + ")包含职位失败！");
		}
		
		String[] temp = jobIds.split(",");
		Integer t = 1;
		for(int i = 0; i < temp.length; i++) {
			UserJob uj = new UserJob();
			uj.setUserId(userId);
			uj.setJobId(temp[i]);
			Integer r = userService.saveJobByUser(uj);
			t = t&r;
		}
		if(t == 1) {
			super.resultMessage.setFlag(super.RESULTMESSAGE_SUCCESS);
			super.resultMessage.setMsg("保存用户职位成功！");
		} else {
			super.resultMessage.setFlag(super.RESULTMESSAGE_FAIL);
			super.resultMessage.setMsg("保存用户职位失败！");
		}
		return super.resultMessage;
	}
	
	/**
	 * 
	 * @description 选择角色
	 * @return String
	 */
	@RequestMapping(value = "/chooseRole", method = RequestMethod.GET)
	public String chooseRole(String userId, Model model) {
		if(StringUtils.isEmpty(userId)) {
			LOGGER.error(this.user_id_empty);
		}
		
		User user = userService.getUserById(userId);
		model.addAttribute("user", user);
		
		List<Map<String, String>> mapList = userService.roleByUserId(userId);
		StringBuffer sb = new StringBuffer();
		if(null != mapList && mapList.size() > 0) {
			for(Map<String, String> map : mapList) {
				sb.append(map.get("ROLEID") + ",");
			}
		}
		String temp = sb.toString();
		if(temp.length() > 0) {
			temp = temp.substring(0, temp.length() - 1);
		}
		model.addAttribute("roleIds", temp);
		return this.CHOOSE_ROLE;
	}
	
	/**
	 * 
	 * @description 保存用户角色
	 * @return ResultMessage
	 */
	@RequestMapping(value = "/saveChooseRole", method = RequestMethod.POST)
	@ResponseBody
	public ResultMessage saveChooseRole(String userId, String roleIds) {
		if(StringUtils.isEmpty(userId)) {
			LOGGER.error(this.user_id_empty);
		}
		
		if(StringUtils.isEmpty(roleIds)) {
			LOGGER.error("角色IDS为空！");
		}
		
		Integer result = userService.deleteRoleByUser(userId);
		if(result > 0) {
			LOGGER.error("删除用户(" + userId + ")包含角色成功！");
		} else {
			LOGGER.error("删除用户(" + userId + ")包含角色失败！");
		}
		
		String[] temp = roleIds.split(",");
		Integer t = 1;
		for(int i = 0; i < temp.length; i++) {
			UserRole ur = new UserRole();
			ur.setUserId(userId);
			ur.setRoleId(temp[i]);
			Integer r = userService.saveRoleByUser(ur);
			t = t&r;
		}
		if(t == 1) {
			super.resultMessage.setFlag(super.RESULTMESSAGE_SUCCESS);
			super.resultMessage.setMsg("保存用户角色成功！");
		} else {
			super.resultMessage.setFlag(super.RESULTMESSAGE_FAIL);
			super.resultMessage.setMsg("保存用户角色失败！");
		}
		return super.resultMessage;
	}
	
	/**
	 * 
	 * @description 密码修改跳转
	 * @return String
	 */
	@RequestMapping(value = "/fmPwd", method = RequestMethod.GET)
	public String modifyPwdForward(HttpServletRequest request, Model model) {
		model.addAttribute("user", super.getCurrentUser(request));
		return this.PASSWORD_MODIFY;
	}
	
	/**
	 * 
	 * @description 密码修改
	 * @return ResultMessage
	 */
	@RequestMapping(value = "/mPwd", method = RequestMethod.POST)
	@ResponseBody
	public ResultMessage modifyPwd(String cfmPwd, HttpServletRequest request) {
		User user = super.getCurrentUser(request);
		user.setUserLoginPwd(Md5Encryption.getInstance().md5Encode(cfmPwd));
		
		Integer result = userService.modifyUserPassword(user);
		if(result > 0) {
			super.resultMessage.setFlag(super.RESULTMESSAGE_SUCCESS);
			super.resultMessage.setMsg("密码修改成功！");
		} else {
			super.resultMessage.setFlag(super.RESULTMESSAGE_FAIL);
			super.resultMessage.setMsg("密码修改失败！");
		}
		return super.resultMessage;
	}
	
	/**
	 * 
	 * @description 密码重置
	 * @return ResultMessage
	 */
	@RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
	@ResponseBody
	public ResultMessage resetPwd(User user) {
		if(StringUtils.isEmpty(user.getId())) {
			LOGGER.error(this.user_id_empty);
		}
		
		Integer result = userService.resetUserPwd(user);
		if(result > 0) {
			super.resultMessage.setFlag(super.RESULTMESSAGE_SUCCESS);
			super.resultMessage.setMsg("密码重置成功！");
		} else {
			super.resultMessage.setFlag(super.RESULTMESSAGE_FAIL);
			super.resultMessage.setMsg("密码重置失败！");
		}
		return super.resultMessage;
	}
	
}
